<template>
  <div>
    <Card>
      <Icon type="help-buoy"></Icon>
      管理员管理详情
    </Card>
    <Card>
      <Form :model="formItem" :label-width="150" ref="formItem" :rules="ruleValidate">
        <Row>
          <i-col span="12">
            <FormItem label="管理员姓名：" prop="adminName">
              <Input style="width: 120px;" v-model="formItem.adminName"/>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="管理员号码：" prop="mobile">
              <Input style="width: 120px;" v-model="formItem.mobile"/>
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <i-col span="12">
            <FormItem label="账号：" prop="account">
              <Input style="width: 120px;" v-model="formItem.account"/>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="管理员类型：" prop="userType">
              <RadioGroup  v-model="formItem.userType" >
                <Radio :label="1">普通管理员</Radio>
                <Radio :label="2">超级管理员</Radio>
              </RadioGroup>
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <i-col span="12">
            <FormItem label="状态：" prop="status">
              <Select v-model="formItem.status" style="width:120px">
                <Option :value="0">禁用</Option>
                <Option :value="1">正常</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="12">
            <template v-if="isAdd">
              <FormItem label="密码：">
                <Button type="primary" @click="pwdRestart('passwordForm')">设置</Button>
              </FormItem>
            </template>
            <template v-else>
              <FormItem label="密码：">
                <Button type="primary" @click="pwdRestart('passwordForm')">重置</Button>
              </FormItem>
            </template>

            <Modal
              v-model="payPwdModal"
              title="输入密码"
              @on-ok="ok('payPwdForm')"
              @on-cancel="cancel('payPwdForm')">
              <Form :model="payPwdForm" :label-width="150" ref="payPwdForm" :rules="ruleValidate2">
                <FormItem label="请输入新的密码:" prop="passwd">
                  <Input v-model="payPwdForm.passwd" type="password" style="width:200px"/>
                </FormItem>
                <FormItem label="请再次输入新的密码:" prop="passwdCheck">
                  <Input v-model="payPwdForm.passwdCheck" type="password" style="width:200px"/>
                </FormItem>
              </Form>
            </Modal>
          </i-col>
        </Row>
        <FormItem label="访问权限：" prop="rights">
          <CheckboxGroup v-model="formItem.rights">
            <Checkbox v-for="item in accessArr" :key="item.name" :label="item.name">{{item.title}}</Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="saveBtn('formItem')">保存</Button>
        </FormItem>
      </Form>
    </Card>
  </div>
</template>

<script>
import { editAdmin, getAdminDetail, addAdmin } from '@/api/admin'
import appRouter from '@/router/routers';
import { isEmpty, isPhoneNumber } from '@/libs/util'

export default {
  name: 'authorization-detail',
  data () {
    const mobileRex = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback(new Error('手机号码不能为空'));
      } else if (!isPhoneNumber(value)) {
        callback(new Error('手机号码格式错误'));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        if (this.payPwdForm.passwdCheck !== '') {
          // 对第二个密码框单独验证
          this.$refs.payPwdForm.validateField('passwdCheck');
        }
        callback();
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.payPwdForm.passwd) {
        callback(new Error('两次密码不同'));
      } else {
        callback();
      }
    };
    return {
      ruleValidate: {
        adminName: [
          {required: true, message: '管理员姓名不能为空', trigger: 'blur'}
        ],
        mobile: [
          {required: true, validator: mobileRex, trigger: 'blur'}
        ],
        account: [
          {required: true, message: '账号不能为空', trigger: 'blur'}
        ],
        userType: [
          {required: true, type: 'number', message: '类型不能为空', trigger: 'change'}
        ],
        status: [
          {required: true,type: 'integer', message: '状态不能为空', trigger: 'change'}
        ],
        rights: [
          { required: true, type: 'array', min: 1, message: '至少选择一种', trigger: 'change' },
        ]
      },
      ruleValidate2: {
        passwd: [{validator: validatePass, trigger: 'blur'}, {
          type: 'string',
          min: 6,
          message: '密码不能短于6位',
          trigger: 'blur'
        }],
        passwdCheck: [{validator: validatePassCheck, trigger: 'blur'}, {
          type: 'string',
          min: 6,
          message: '密码不能短于6位',
          trigger: 'blur'
        }]
      },
      formItem: {
        adminName: '',
        mobile: '',
        account: '',
        passWord: '',
        status: 0,
        accessNum: 5,
        rights: []
      },
      payPwdForm: {
        passwd: '',
        passwdCheck: ''
      },
      accessArr:[],
      isAdd: true,
      payPwdModal: false
    };
  },
  methods: {
    getData() {
      getAdminDetail(this.$route.query.id).then(data => {
        this.formItem = data
        if(!data.rights){
          this.formItem.rights = [];
        }
        if(data.rights[0] === '') {
          this.formItem.rights = [];
        }
      })
    },
    // 保存
    saveBtn(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let params = this.formItem
          if(this.isAdd){
            // 添加保存
            if(!this.formItem.password){
              this.$Message.info('请设置登录密码');
              return;
            }
            addAdmin(params).then(res => {
              this.$Message.success('增加成功');
              this.$router.go(-1)
            });
          }else{
            delete params['password']
            // 修改保存
            editAdmin(params).then(data => {
              if (data.id) {
                this.$Message.success('保存成功');
                this.getData();
              }
            });
          }
        } else {
          this.$Message.error('保存失败');
        }
      });
    },
    // 获取列表
    getAccess() {
      appRouter.forEach((item) => {
        if(item.title){
          let {name, title, access} = {
            name : item.name,
            title : item.title,
            access : item.access
          }
          this.accessArr.push({
            name, title, access
          })
        }
      })
    },
    pwdRestart(name) {
      this.payPwdModal = true;
      this.$refs['payPwdForm'].resetFields();
    },
    //确认修改密码
    ok(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if(!this.isAdd){
            let params = this.formItem
            params.password = this.payPwdForm.passwdCheck
            editAdmin(params).then(() => {
              this.$Message.success('修改密码成功');
            })
          }
          this.formItem.password = this.payPwdForm.passwdCheck;
        } else {
          this.$Message.error('修改密码失败');
        }
      });
    },
    cancel(name) {
      this.$refs[name].resetFields();
    }

  },
  mounted() {
    if(this.$route.query.id){
      this.isAdd = false;
      this.getData();
    }else{
      this.isAdd = true;
    }
    this.getAccess();
  }
}
</script>

<style scoped>

</style>
